//
//  YAComposeController.swift
//  添加视图辅助开发
//
//  Created by 鱼龙之梦 on 15/9/10.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit
import SVProgressHUD
class YAComposeController: UIViewController,UITextViewDelegate {
     //MARK:--- 动态改变工具栏的位置
    private var toolbarBottomCons:NSLayoutConstraint?
    //问题：为什么要设文本视图约束
    private var textViewBottomCons:NSLayoutConstraint?
    //问题：为什么要设照片选择视图的高度约束
    private var picViewHeightCons:NSLayoutConstraint?
    @objc private func close(){
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    private lazy var keyboardVC: YAEmoticonsVC = YAEmoticonsVC { [weak self] (emoticon) -> () in
        print(emoticon.chs)
        self?.textView.insertEmoticon(emoticon)
    }
    @objc private func switchEmoticonKeyboard(){
        textView.resignFirstResponder()
        printLog(textView.inputView)
        textView.inputView = (textView.inputView == nil) ? keyboardVC.view : nil
        textView.becomeFirstResponder()
    }
    @objc private func selectPicture(){
        printLog("选择照片")
        //删除文本视图和toolbar之间的约束
        view.removeConstraint(textViewBottomCons!)
        //设置文本视图和照片视图之间的约束
        textViewBottomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: .Equal, toItem: PicVc.view, attribute: .Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomCons!)
        //设置高度约束
        picViewHeightCons?.constant = UIScreen.mainScreen().bounds.height * 0.7
        //关闭键盘
        textView.resignFirstResponder()
        
        //动画更新约束
        UIView.animateWithDuration(0.25){
            self.view.layoutIfNeeded()
        }
        
    }
    @objc private func sendStatus()
    {
        printLog("发送微博")
        let text = textView.emoticonText
        navigationItem.rightBarButtonItem?.enabled = false
        YANetworking.sharedTools.sendStatus(text, image: PicVc.pictures.last).subscribeNext({ (result) -> Void in
            self.navigationItem.rightBarButtonItem?.enabled = true
            //刚刚发送成功的微博数据字典
            printLog(result)
            }, error: { (error) -> Void in
                printLog(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }) { () -> Void in
                self.close()
        }
    }
     //MARK:--- 判断文本控件上是否有文字
    func textViewDidChange(textView: UITextView) {
        placeholderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
     //MARK:--- 在视图将要显示的时候 激活键盘
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //如果用户已经选择了照片，就不再激活键盘 
        if picViewHeightCons?.constant  == 0{
            textView.becomeFirstResponder()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //注意:注册键盘通知 UIKeyboardWillChangeFrameNotification
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    @objc private func keyboardChanged(noti:NSNotification){
        //printLog(noti)
        //让keyboard曲线变化
        let curve = noti.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
        
        //注意：oc中将结构体保存在字典中 保存成NSValue
        //注意：从UIKeyboardFrameEndUserInfoKey拿frame值
        let  rect = noti.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        //注意：从UIKeyboardAnimationDurationUserInfoKey 拿延迟时间
        let duration = noti.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        //注意：设置工具栏位置
        toolbarBottomCons?.constant = -UIScreen.mainScreen().bounds.height  + rect.origin.y
        
        UIView.animateWithDuration(duration){
            //增加动画曲线
            UIView.setAnimationCurve(UIViewAnimationCurve.init(rawValue: curve)!)
            self.view.layoutIfNeeded()//注意：改变约束后，要调用这个方法好才有效
        }
        //拿到toolbar的动画时长
        let anim = toolbar.layer.animationForKey("position")
       // printLog("动画时长\(anim?.duration)")
        
    }
    override func loadView() {
        view = UIView()
        //注意：将自动调整scrollView的缩进取消 ??
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor.whiteColor()
        prepareNav()
        prepareToolBar()
        prepareTextView()
        preparePictrue()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //MARK:--- 准备添加图片区域
    private func preparePictrue(){
        addChildViewController(PicVc)
        //view.addSubview(PicVc.view)//这样会导致工具栏被隐藏
        view.insertSubview(PicVc.view, belowSubview: toolbar)
        //注意：布局 放在本视图的底部
        let size = UIScreen.mainScreen().bounds.size
        let cons = PicVc.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: size.width, height: 0))//size.height*0.6)
        //记录照片视图的高度约束
        picViewHeightCons = PicVc.view.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)

    }
    //MARK:--- 准备导航栏
    private func prepareNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style:
            .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style:
            .Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        //标题视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        let titleLabel = UILabel(title: "发微博", color: UIColor.orangeColor(), fontSize: 15)
        
        let nameLabel = UILabel(title: YAUserAcountVM.sharedUserAccount.userAcount?.name, color: UIColor.lightGrayColor(), fontSize: 13)
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        //布局
        
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        navigationItem.titleView = titleView
    }
    //设置工具栏
    private func prepareToolBar(){
        //let toolbar = UIToolbar()
        view.addSubview(toolbar)
        let w = UIScreen.mainScreen().bounds.width
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: 44))
        
        toolbarBottomCons = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        //定义一个图像名称数组
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","action":"switchEmoticonKeyboard"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings{
            //let button = UIButton(imageName: dict["imageName"]!)
//            if let actionName = dict["action"]{
//                button.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
//            }
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["action"]))
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
    }
    private func  prepareTextView(){
        view.addSubview(textView)
        
        textView.translatesAutoresizingMaskIntoConstraints = false
        //textView将参照 顶部的控件 工具类的控件 屏幕  //注意：用字典盛放参照视图
        let viewDict:[String:AnyObject] = ["top":topLayoutGuide,"tb":toolbar,"tv":textView]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tv]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[top]-0-[tv]", options: [], metrics: nil, views: viewDict))
        textViewBottomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolbar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomCons!)
        textView.addSubview(placeholderLabel)
        
        placeholderLabel.frame = CGRect(origin: CGPoint(x: 5, y: 8), size: placeholderLabel.bounds.size)
    }
     //MARK:--- 懒加载控件
    //文本视图
    private lazy var textView:UITextView = {
        let tv = UITextView()
        tv.delegate = self
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        tv.alwaysBounceVertical = true
        //拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return tv
    }()
    //占位标签
    private lazy var placeholderLabel:UILabel =
        UILabel(title: "分享新鲜事...", color: UIColor.lightGrayColor(), fontSize: 18)
    
    //工具栏
    private lazy var toolbar = UIToolbar()
    //懒加载 图片选择控制器
    private lazy var PicVc = YASelectPicController()
}
